<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>工单API连接测试</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            border-bottom: 3px solid #409eff;
            padding-bottom: 10px;
        }
        button {
            background: #409eff;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin: 10px 5px;
        }
        button:hover {
            background: #66b1ff;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 4px;
            white-space: pre-wrap;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            line-height: 1.6;
            max-height: 500px;
            overflow-y: auto;
        }
        .success {
            background: #f0f9ff;
            border: 2px solid #67c23a;
            color: #67c23a;
        }
        .error {
            background: #fef0f0;
            border: 2px solid #f56c6c;
            color: #f56c6c;
        }
        .info {
            background: #f4f4f5;
            border: 2px solid #909399;
            color: #606266;
        }
        .step {
            margin: 20px 0;
            padding: 15px;
            background: #f9f9f9;
            border-left: 4px solid #409eff;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 工单API连接测试工具</h1>
        
        <div class="step">
            <h3>步骤1: 检查配置和Token</h3>
            <button onclick="checkBasic()">检查基础信息</button>
            <div id="basicResult" class="result"></div>
        </div>

        <div class="step">
            <h3>步骤2: 测试后端连接</h3>
            <button onclick="testBackend()">测试后端服务</button>
            <div id="backendResult" class="result"></div>
        </div>

        <div class="step">
            <h3>步骤3: 测试用户API（对比）</h3>
            <button onclick="testUsersAPI()">测试用户API</button>
            <div id="usersResult" class="result"></div>
        </div>

        <div class="step">
            <h3>步骤4: 测试工单API</h3>
            <button onclick="testTicketsAPI()">测试工单API</button>
            <div id="ticketsResult" class="result"></div>
        </div>

        <div class="step">
            <h3>步骤5: 完整诊断</h3>
            <button onclick="fullDiagnosis()">运行完整诊断</button>
            <div id="fullResult" class="result"></div>
        </div>
    </div>

    <script>
        const API_BASE_URL = 'http://localhost:9090/api';

        function log(elementId, message, type = 'info') {
            const element = document.getElementById(elementId);
            element.className = `result ${type}`;
            element.textContent = message;
        }

        async function checkBasic() {
            let result = '=== 基础信息检查 ===\n\n';
            
            // 检查Token
            const token = localStorage.getItem('token');
            result += `Token存在: ${!!token ? '✅ 是' : '❌ 否'}\n`;
            if (token) {
                result += `Token长度: ${token.length}\n`;
                try {
                    const parts = token.split('.');
                    if (parts.length === 3) {
                        const payload = JSON.parse(atob(parts[1]));
                        result += `Token用户: ${payload.sub || payload.username || 'N/A'}\n`;
                        result += `Token过期: ${payload.exp ? new Date(payload.exp * 1000).toLocaleString() : 'N/A'}\n`;
                    }
                } catch (e) {
                    result += `Token解析失败\n`;
                }
            }
            
            // 检查用户信息
            const userInfo = localStorage.getItem('user_info');
            if (userInfo) {
                try {
                    const user = JSON.parse(userInfo);
                    result += `\n用户信息:\n`;
                    result += `  用户名: ${user.username}\n`;
                    result += `  角色: ${user.role}\n`;
                    result += `  ID: ${user.id}\n`;
                } catch (e) {
                    result += `用户信息解析失败\n`;
                }
            }
            
            result += `\nAPI配置:\n`;
            result += `  API_BASE_URL: ${API_BASE_URL}\n`;
            result += `  工单API URL: ${API_BASE_URL}/tickets\n`;
            
            log('basicResult', result, token ? 'success' : 'error');
        }

        async function testBackend() {
            log('backendResult', '正在测试后端连接...', 'info');
            
            const tests = [
                { name: '后端根路径', url: 'http://localhost:9090/' },
                { name: 'API根路径', url: API_BASE_URL },
                { name: '健康检查', url: 'http://localhost:9090/actuator/health' }
            ];
            
            let result = '=== 后端连接测试 ===\n\n';
            
            for (const test of tests) {
                try {
                    const startTime = Date.now();
                    const response = await fetch(test.url, {
                        method: 'GET',
                        headers: { 'Content-Type': 'application/json' }
                    });
                    const endTime = Date.now();
                    
                    result += `${test.name}:\n`;
                    result += `  URL: ${test.url}\n`;
                    result += `  状态: ${response.status} ${response.statusText}\n`;
                    result += `  响应时间: ${endTime - startTime}ms\n`;
                    result += `  结果: ${response.ok ? '✅ 可访问' : '❌ 不可访问'}\n\n`;
                } catch (error) {
                    result += `${test.name}:\n`;
                    result += `  URL: ${test.url}\n`;
                    result += `  错误: ${error.message}\n`;
                    result += `  结果: ❌ 无法连接\n\n`;
                }
            }
            
            log('backendResult', result, 'info');
        }

        async function testUsersAPI() {
            log('usersResult', '正在测试用户API...', 'info');
            
            try {
                const token = localStorage.getItem('token');
                const url = `${API_BASE_URL}/users?page=0&size=5`;
                
                const startTime = Date.now();
                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': token ? `Bearer ${token}` : ''
                    }
                });
                const endTime = Date.now();
                
                let result = `=== 用户API测试 ===\n\n`;
                result += `请求URL: ${url}\n`;
                result += `HTTP状态: ${response.status} ${response.statusText}\n`;
                result += `响应时间: ${endTime - startTime}ms\n\n`;
                
                if (response.ok) {
                    const data = await response.json();
                    result += `响应数据:\n${JSON.stringify(data, null, 2)}\n\n`;
                    result += `✅ 用户API测试成功！\n`;
                    if (data.success && data.data && data.data.content) {
                        result += `用户数量: ${data.data.content.length}\n`;
                    }
                    log('usersResult', result, 'success');
                } else {
                    const errorText = await response.text();
                    result += `❌ 请求失败！\n`;
                    result += `错误响应: ${errorText}\n`;
                    log('usersResult', result, 'error');
                }
            } catch (error) {
                let result = `❌ 用户API测试失败:\n${error.message}\n`;
                if (error.message.includes('Failed to fetch')) {
                    result += `\n可能的原因:\n`;
                    result += `1. 后端服务未启动\n`;
                    result += `2. 网络连接问题\n`;
                    result += `3. CORS跨域问题\n`;
                }
                log('usersResult', result, 'error');
            }
        }

        async function testTicketsAPI() {
            log('ticketsResult', '正在测试工单API...', 'info');
            
            try {
                const token = localStorage.getItem('token');
                const url = `${API_BASE_URL}/tickets?page=0&size=10`;
                
                let result = `=== 工单API测试 ===\n\n`;
                result += `请求URL: ${url}\n`;
                result += `Token存在: ${!!token ? '✅ 是' : '❌ 否'}\n`;
                if (token) {
                    result += `Token长度: ${token.length}\n`;
                }
                result += `\n`;
                
                const startTime = Date.now();
                const response = await fetch(url, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': token ? `Bearer ${token}` : ''
                    }
                });
                const endTime = Date.now();
                
                result += `HTTP状态: ${response.status} ${response.statusText}\n`;
                result += `响应时间: ${endTime - startTime}ms\n`;
                result += `Content-Type: ${response.headers.get('content-type')}\n\n`;
                
                if (!response.ok) {
                    const errorText = await response.text();
                    result += `❌ 请求失败！\n`;
                    result += `错误响应: ${errorText}\n\n`;
                    
                    if (response.status === 401) {
                        result += `💡 问题: 认证失败\n`;
                        result += `💡 解决: 请重新登录\n`;
                    } else if (response.status === 403) {
                        result += `💡 问题: 权限不足\n`;
                        result += `💡 解决: 检查用户角色权限\n`;
                    } else if (response.status === 404) {
                        result += `💡 问题: API路径不存在\n`;
                        result += `💡 解决: 检查后端路由配置\n`;
                    } else if (response.status === 500) {
                        result += `💡 问题: 服务器内部错误\n`;
                        result += `💡 解决: 查看后端日志\n`;
                    }
                    
                    log('ticketsResult', result, 'error');
                    return;
                }
                
                const data = await response.json();
                result += `响应数据:\n${JSON.stringify(data, null, 2)}\n\n`;
                
                if (data.success) {
                    result += `✅ 工单API测试成功！\n`;
                    if (data.data && data.data.content) {
                        result += `工单数量: ${data.data.content.length}\n`;
                        result += `总数: ${data.data.totalElements}\n`;
                    }
                    log('ticketsResult', result, 'success');
                } else {
                    result += `⚠️ 响应success为false\n`;
                    if (data.message) {
                        result += `错误消息: ${data.message}\n`;
                    }
                    log('ticketsResult', result, 'error');
                }
            } catch (error) {
                let result = `❌ 工单API测试失败:\n${error.message}\n\n`;
                
                if (error.message.includes('Failed to fetch') || error.message.includes('NetworkError')) {
                    result += `可能的原因:\n`;
                    result += `1. 后端服务未启动 (检查 http://localhost:9090)\n`;
                    result += `2. 网络连接问题\n`;
                    result += `3. CORS跨域问题\n`;
                    result += `4. 请求超时\n`;
                    result += `\n💡 建议:\n`;
                    result += `- 打开浏览器开发者工具 (F12)\n`;
                    result += `- 查看 Network 标签\n`;
                    result += `- 找到 /tickets 请求\n`;
                    result += `- 查看请求状态和响应\n`;
                } else {
                    result += `错误详情: ${error.stack || error}`;
                }
                
                log('ticketsResult', result, 'error');
            }
        }

        async function fullDiagnosis() {
            log('fullResult', '正在运行完整诊断...', 'info');
            
            let result = '=== 完整诊断报告 ===\n\n';
            
            // 1. 基础信息
            result += '1. 基础信息检查\n';
            result += '─────────────────────\n';
            const token = localStorage.getItem('token');
            result += `Token: ${token ? '✅ 存在' : '❌ 不存在'}\n`;
            result += `API地址: ${API_BASE_URL}\n\n`;
            
            // 2. 后端连接
            result += '2. 后端连接测试\n';
            result += '─────────────────────\n';
            try {
                const backendResponse = await fetch('http://localhost:9090/', { method: 'HEAD' });
                result += `后端服务: ${backendResponse.ok ? '✅ 可访问' : '❌ 不可访问'}\n`;
            } catch (e) {
                result += `后端服务: ❌ 无法连接\n`;
            }
            result += '\n';
            
            // 3. 用户API测试
            result += '3. 用户API测试\n';
            result += '─────────────────────\n';
            try {
                const usersResponse = await fetch(`${API_BASE_URL}/users?page=0&size=1`, {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                result += `状态: ${usersResponse.status}\n`;
                result += `结果: ${usersResponse.ok ? '✅ 成功' : '❌ 失败'}\n`;
            } catch (e) {
                result += `结果: ❌ ${e.message}\n`;
            }
            result += '\n';
            
            // 4. 工单API测试
            result += '4. 工单API测试\n';
            result += '─────────────────────\n';
            try {
                const ticketsResponse = await fetch(`${API_BASE_URL}/tickets?page=0&size=1`, {
                    headers: { 'Authorization': `Bearer ${token}` }
                });
                result += `状态: ${ticketsResponse.status}\n`;
                result += `结果: ${ticketsResponse.ok ? '✅ 成功' : '❌ 失败'}\n`;
                
                if (!ticketsResponse.ok) {
                    const errorText = await ticketsResponse.text();
                    result += `错误: ${errorText.substring(0, 200)}\n`;
                } else {
                    const data = await ticketsResponse.json();
                    result += `响应格式: ${data.success ? '✅ 正确' : '❌ 异常'}\n`;
                }
            } catch (e) {
                result += `结果: ❌ ${e.message}\n`;
            }
            result += '\n';
            
            // 5. 总结
            result += '5. 诊断总结\n';
            result += '─────────────────────\n';
            result += `如果用户API成功但工单API失败，可能的原因:\n`;
            result += `1. 后端工单控制器路由配置问题\n`;
            result += `2. 工单API需要特殊权限\n`;
            result += `3. 后端服务中工单相关代码有异常\n`;
            result += `4. 数据库连接或查询问题\n`;
            
            log('fullResult', result, 'info');
        }
    </script>
</body>
</html>


